// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  try {
    const { action } = event

    switch (action) {
      // 发布商品
      case 'publish':
        return await publishGoods(event, wxContext)
      
      // 获取商品列表
      case 'getList':
        return await getGoodsList(event, wxContext)
      
      // 获取商品详情
      case 'getDetail':
        return await getGoodsDetail(event, wxContext)
      
      // 更新商品
      case 'update':
        return await updateGoods(event, wxContext)
      
      // 删除商品
      case 'delete':
        return await deleteGoods(event, wxContext)
      
      // 修改商品状态
      case 'updateStatus':
        return await updateGoodsStatus(event, wxContext)
      
      // 搜索商品
      case 'search':
        return await searchGoods(event, wxContext)
      
      // 收藏商品
      case 'favorite':
        return await favoriteGoods(event, wxContext)
      
      // 取消收藏
      case 'unfavorite':
        return await unfavoriteGoods(event, wxContext)
      
      // 增加浏览量
      case 'addViewCount':
        return await addViewCount(event, wxContext)
      
      default:
        return {
          code: -1,
          msg: '无效的action参数'
        }
    }
  } catch (err) {
    console.error(err)
    return {
      code: -1,
      msg: '服务器错误',
      error: err
    }
  }
}

/**
 * 发布商品
 */
async function publishGoods(event, wxContext) {
  const { OPENID } = wxContext
  const { title, category, price, condition_level, description, images, trade_method, trade_location, contact_wechat, contact_qq, contact_phone, qrcode_image } = event

  try {
    const result = await db.collection('goods').add({
      data: {
        openid: OPENID,
        title,
        category,
        price: parseFloat(price),
        condition_level,
        description: description || '',
        images: images || [],
        trade_method,
        trade_location,
        contact_wechat,
        contact_qq: contact_qq || '',
        contact_phone: contact_phone || '',
        qrcode_image: qrcode_image || '',
        status: 1, // 1-在售
        view_count: 0,
        favorite_count: 0,
        created_at: new Date(),
        updated_at: new Date()
      }
    })

    return {
      code: 0,
      msg: '发布成功',
      data: {
        id: result._id
      }
    }
  } catch (err) {
    console.error('发布商品失败：', err)
    return {
      code: -1,
      msg: '发布失败',
      error: err
    }
  }
}

/**
 * 获取商品列表
 */
async function getGoodsList(event, wxContext) {
  const { page = 1, pageSize = 20, category, sort = 'latest', status = 1 } = event

  try {
    const skip = (page - 1) * pageSize
    
    // 构建查询条件
    let where = { status }
    if (category) {
      where.category = category
    }

    // 排序
    let orderBy = 'created_at'
    let order = 'desc'
    if (sort === 'price_asc') {
      orderBy = 'price'
      order = 'asc'
    } else if (sort === 'price_desc') {
      orderBy = 'price'
      order = 'desc'
    } else if (sort === 'popular') {
      orderBy = 'favorite_count'
      order = 'desc'
    }

    const result = await db.collection('goods')
      .where(where)
      .orderBy(orderBy, order)
      .skip(skip)
      .limit(pageSize)
      .get()

    // 判断是否还有更多数据
    const hasMore = result.data.length >= pageSize

    return {
      code: 0,
      msg: '获取成功',
      data: {
        list: result.data,
        hasMore: hasMore
      }
    }
  } catch (err) {
    console.error('获取商品列表失败：', err)
    return {
      code: -1,
      msg: '获取失败',
      error: err
    }
  }
}

/**
 * 获取商品详情
 */
async function getGoodsDetail(event, wxContext) {
  const { id } = event

  try {
    const result = await db.collection('goods').doc(id).get()

    if (!result.data) {
      return {
        code: -1,
        msg: '商品不存在'
      }
    }

    return {
      code: 0,
      msg: '获取成功',
      data: result.data
    }
  } catch (err) {
    console.error('获取商品详情失败：', err)
    return {
      code: -1,
      msg: '获取失败',
      error: err
    }
  }
}

/**
 * 更新商品
 */
async function updateGoods(event, wxContext) {
  const { OPENID } = wxContext
  const { id, ...updateData } = event

  try {
    // 验证权限
    const goods = await db.collection('goods').doc(id).get()
    if (goods.data.openid !== OPENID) {
      return {
        code: -1,
        msg: '无权限修改'
      }
    }

    delete updateData.action
    updateData.updated_at = new Date()

    await db.collection('goods').doc(id).update({
      data: updateData
    })

    return {
      code: 0,
      msg: '更新成功'
    }
  } catch (err) {
    console.error('更新商品失败：', err)
    return {
      code: -1,
      msg: '更新失败',
      error: err
    }
  }
}

/**
 * 删除商品
 */
async function deleteGoods(event, wxContext) {
  const { OPENID } = wxContext
  const { id } = event

  try {
    // 验证权限
    const goods = await db.collection('goods').doc(id).get()
    if (goods.data.openid !== OPENID) {
      return {
        code: -1,
        msg: '无权限删除'
      }
    }

    // 删除商品记录
    await db.collection('goods').doc(id).remove()

    // 删除所有相关的收藏记录
    try {
      await db.collection('favorites')
        .where({
          item_type: 1, // 1-商品
          item_id: id
        })
        .remove()
      console.log('已删除商品相关的收藏记录')
    } catch (err) {
      console.error('删除收藏记录失败：', err)
      // 即使删除收藏失败，也不影响商品删除
    }

    return {
      code: 0,
      msg: '删除成功'
    }
  } catch (err) {
    console.error('删除商品失败：', err)
    return {
      code: -1,
      msg: '删除失败',
      error: err
    }
  }
}

/**
 * 修改商品状态
 */
async function updateGoodsStatus(event, wxContext) {
  const { OPENID } = wxContext
  const { id, status } = event

  try {
    // 验证权限
    const goods = await db.collection('goods').doc(id).get()
    if (goods.data.openid !== OPENID) {
      return {
        code: -1,
        msg: '无权限修改'
      }
    }

    await db.collection('goods').doc(id).update({
      data: {
        status,
        updated_at: new Date()
      }
    })

    return {
      code: 0,
      msg: '修改成功'
    }
  } catch (err) {
    console.error('修改商品状态失败：', err)
    return {
      code: -1,
      msg: '修改失败',
      error: err
    }
  }
}

/**
 * 搜索商品（简化版 - 只搜索标题）
 */
async function searchGoods(event, wxContext) {
  const { keyword, page = 1, pageSize = 20, category, sort = 'latest' } = event

  try {
    const skip = (page - 1) * pageSize
    
    console.log('搜索参数：', { keyword, page, pageSize, category, sort })
    
    // 构建查询条件 - 先用最简单的方式
    let where = {
      status: 1,
      title: new RegExp(keyword, 'i')  // 使用原生 RegExp
    }
    
    if (category) {
      where.category = category
    }

    console.log('查询条件：', where)

    // 排序
    let orderBy = 'created_at'
    let order = 'desc'
    if (sort === 'price_asc') {
      orderBy = 'price'
      order = 'asc'
    } else if (sort === 'price_desc') {
      orderBy = 'price'
      order = 'desc'
    } else if (sort === 'popular') {
      orderBy = 'favorite_count'
      order = 'desc'
    }

    const result = await db.collection('goods')
      .where(where)
      .orderBy(orderBy, order)
      .skip(skip)
      .limit(pageSize)
      .get()

    console.log('搜索结果数量：', result.data.length)

    // 判断是否还有更多数据
    const hasMore = result.data.length >= pageSize

    return {
      code: 0,
      msg: '搜索成功',
      data: {
        list: result.data,
        hasMore: hasMore,
        total: result.data.length
      }
    }
  } catch (err) {
    console.error('搜索商品失败：', err)
    return {
      code: -1,
      msg: '搜索失败',
      error: err.toString()
    }
  }
}

/**
 * 收藏商品
 */
async function favoriteGoods(event, wxContext) {
  const { OPENID } = wxContext
  const { goods_id } = event

  try {
    // 检查是否已收藏
    const existResult = await db.collection('favorites').where({
      openid: OPENID,
      item_type: 1,
      item_id: goods_id
    }).get()

    if (existResult.data.length > 0) {
      return {
        code: -1,
        msg: '已收藏过了'
      }
    }

    // 添加收藏记录
    await db.collection('favorites').add({
      data: {
        openid: OPENID,
        item_type: 1, // 1-商品
        item_id: goods_id,
        created_at: new Date()
      }
    })

    // 增加商品收藏数
    await db.collection('goods').doc(goods_id).update({
      data: {
        favorite_count: _.inc(1)
      }
    })

    return {
      code: 0,
      msg: '收藏成功'
    }
  } catch (err) {
    console.error('收藏商品失败：', err)
    return {
      code: -1,
      msg: '收藏失败',
      error: err
    }
  }
}

/**
 * 取消收藏
 */
async function unfavoriteGoods(event, wxContext) {
  const { OPENID } = wxContext
  const { goods_id } = event

  try {
    // 删除收藏记录
    await db.collection('favorites').where({
      openid: OPENID,
      item_type: 1,
      item_id: goods_id
    }).remove()

    // 减少商品收藏数
    await db.collection('goods').doc(goods_id).update({
      data: {
        favorite_count: _.inc(-1)
      }
    })

    return {
      code: 0,
      msg: '取消收藏成功'
    }
  } catch (err) {
    console.error('取消收藏失败：', err)
    return {
      code: -1,
      msg: '取消收藏失败',
      error: err
    }
  }
}

/**
 * 增加浏览量
 */
async function addViewCount(event, wxContext) {
  const { id } = event

  try {
    await db.collection('goods').doc(id).update({
      data: {
        view_count: _.inc(1)
      }
    })

    return {
      code: 0,
      msg: '成功'
    }
  } catch (err) {
    console.error('增加浏览量失败：', err)
    return {
      code: -1,
      msg: '失败',
      error: err
    }
  }
}

